#ifndef CHAT_SERVICE_SERVER_PROCESSOR_H_
#define CHAT_SERVICE_SERVER_PROCESSOR_H_
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/transport/THttpServer.h>
#include "gen-cpp/ChatService.h"
#include "server/RequestContext.h"

namespace atp = apache::thrift::protocol;
namespace att = apache::thrift::transport;

class ChatServiceServerProcessor : public chat::ChatServiceProcessor {
public:
ChatServiceServerProcessor(boost::shared_ptr<chat::ChatServiceIf> iface) : chat::ChatServiceProcessor(iface) {
    
  }
  virtual bool dispatchCall(::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, const std::string& fname, int32_t seqid, void* callContext) {
    // Server端每收到一个非EmptyRequest，都应该回发送者一个Response
    const std::string kEmptyRequest = "SendEmptyRequest";
    if (fname == kEmptyRequest) {
      return chat::ChatServiceProcessor::dispatchCall(iprot, oprot, fname, seqid, callContext);
    }

    // 这里可以优化
    boost::shared_ptr<att::TMemoryBuffer> outTrans(new att::TMemoryBuffer());
    boost::shared_ptr<att::TTransport> trans(new att::THttpServer(outTrans));
    boost::shared_ptr<atp::TProtocol> prot(new atp::TBinaryProtocol(trans));
    trans->open();
    chat::ChatServiceClient client(prot);
    // 拿到client了,调用下发，将数据写到memory buffer
    // 注意到transport用的http server，所以写出的是http response

    server::RequestContext* req_context = (server::RequestContext*) callContext;
    if (fname == "SendMsg") {
      chat::ChatService_SendMsg_args args;
      args.read(iprot);
      iprot->readMessageEnd();
      uint32_t bytes = iprot->getTransport()->readEnd();
      client.SendMsg(args.req);
      req_context->toid_ = args.req.toid;
    } else {
      return chat::ChatServiceProcessor::dispatchCall(iprot, oprot, fname, seqid, callContext);
    }
    req_context->formated_resp_ =  outTrans->getBufferAsString();
    return true;
  }
  };
#endif
